<?php

namespace app\controller;

use app\service\UserService;
use support\Response;
use think\facade\Db;

/**
 * 登录控制器
 */
class LoginController extends Base
{
    //免登录白名单
    protected array $noNeedLogin = ['index'];

    //用户登录
    public function index()
    {
        // 获取参数
        $code = $this->request->post('code', '10001');
        if (empty($code)) {
            return json(apiError('参数错误'));
        }

        $platform = $this->request->post('platform', 0);
        $nickname = $this->request->post('nickname', '测试用户_' . rand(1000, 10000));
        $avatar = $this->request->post('avatar', 'https://ylgys.vip.hnhxzkj.com/wenzhouwaixing.jpg');

        // 启动事务
        try {
            $res = Db::transaction(function () use ($code, $platform, $nickname, $avatar) {
                $userService = new UserService();
                $res = $userService->toLoginByCode($code, $platform, $nickname, $avatar);

                if (empty($res['code']) || $res['code'] !== 1) {
                    throw new \Exception('登录失败');
                }
                return $res;
            });

            return json($res);

        } catch (\Throwable $e) {
            return json(apiError('系统错误: ' . $e->getMessage()));
        }
    }
}
